<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2023/6/17
 * Time: 15:07
 */
namespace app\admin\controller;

use app\middleware\AdminCheck;
use think\facade\Db;

class Carnos {

    protected $middleware = [
        AdminCheck::class => ['except' 	=> [] ]
    ];

    /**
     * @return \think\response\Json
     */
    public function add() {
        validateParam('car_id,car_no,region_id','car_id,car_no,region_id');
        if (Db::name('cars')->where('id', input('car_id'))->count() == 0) {
            return success('车辆信息未找到');
        }
        if (Db::name('car_nos')->where('car_no', input('car_no'))->count() > 0) {
            return success('车牌号已存在');
        }
        $data['car_id']=input('car_id');
        $data['car_no']=input('car_no');
        $data['region_id'] = input('region_id');

        $res = Db::name('car_nos')->insert($data);
        return success('添加成功', $res);
    }

    /**
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(){
        $carInfo = Db::name('cars')->where('id', input('car_id'))->find();
        $query = Db::name('car_nos')
            ->join('region', 'car_nos.region_id = region.region_id')
            ->where('is_deleted', '=', 0)
            ->where('car_id', '=', input('car_id'));

        $list = $query
            ->fieldRaw('car_nos.*, region.region_name')
            ->order('id desc')
            ->select()->toArray();

        foreach ($list as &$val) {
            $val['car_name'] = $carInfo['car_name'] . $carInfo['type_name'];
        }

        return success('车牌列表', $list);
    }

    /**
     * 更新上下架状态
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function updateStatus() {
        validateParam('id','id');
        Db::name('car_nos')->where('id', input('id'))->update(['status' => input('status', 0)]);
        return success('更新成功');
    }

    /**
     * 删除
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function delete() {
        validateParam('id','id');
        $res = Db::name('car_nos')->where('id', input('id'))->update(['is_deleted' => 1]);
        return success('删除成功');
    }
}